package random

import (
	"fmt"
	"os"
	"time"

	"qingbing/xzutils/utils"
)

// 获取随机字符串
// 可通过掩码选中字符串, mask 7 => 1,2,4, mask 3 => 1,2, mask 5 => 1, 4
func String(length uint8, mask uint8) (str string) {
	lib := map[uint8][]rune{
		1:  []rune("0123456789"),
		2:  []rune("abcdedghijklmnopqrstuvwxyz"),
		4:  []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
		8:  []rune("-=$"),
		16: []rune("0123456789ABCDEF"),
	}
	letters := []rune{}
	for ki, cs := range lib {
		mk := mask & ki
		if ki == mk {
			letters = append(letters, cs...)
		}
	}
	letterLen := len(letters)
	if 0 == letterLen {
		return
	}
	bs := make([]rune, length)
	for i := 0; i < int(length); i++ {
		bs[i] = letters[Int(letterLen)]
	}
	return string(bs)
}

// 根据 当前时间+服务IP+当前进程ID 计算一个唯一 id
func Uniqid() string {
	// 时间计算
	now := fmt.Sprintf("%X", time.Now().UnixNano())
	// 服务器端 ip 计算
	var ip string = ""
	if longIp, err := utils.IPString2Long(utils.ServerIp()); err == nil {
		ip = fmt.Sprintf("%X", longIp)
	} else if hostname, err := os.Hostname(); err == nil {
		ip = utils.StringToHex(hostname) // 找不到 IP 用主机名代替
	}
	// 当前 进程ID 计算
	pid := fmt.Sprintf("%X", os.Getpid())
	unq := now + ip + pid
	length := len(unq)
	if length >= 32 {
		return unq[length-32:]
	}
	return unq + String(uint8(32-length), 16)
}
